package org.example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test2 {
    //leetcode 40 组合总和II https://leetcode.cn/problems/combination-sum-ii/description/
    public List<List<Integer>> ret;
    public List<Integer> list;
    public int sum;
    public List<List<Integer>> combinationSum2(int[] candidates, int target) {
        ret = new ArrayList<>();
        list = new ArrayList<>();
        Arrays.sort(candidates);
        backtracking(candidates,target,0);
        return ret;
    }

    public void backtracking(int[] candidates, int target, int start) {
        if (sum > target) return;
        if (sum == target) {
            ret.add(new ArrayList<>(list));
            return;
        }

        int prev = 0;
        //剪枝操作 sum + candidates[i] <= target
        for (int i = start; i < candidates.length && sum + candidates[i] <= target; i++) {
            if (candidates[i] == prev) continue;
            sum += candidates[i];
            list.add(candidates[i]);
            backtracking(candidates,target,i + 1);
            sum -= candidates[i];
            list.remove(list.size() - 1);
            prev = candidates[i];
        }
    }
}
